package com.fourhats.dao.impl;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.fourhats.dao.UserDAO;
import com.fourhats.model.User;

@Repository
public class UserDaoImpl extends GenericDAOImpl<User, Long> implements UserDAO {

	protected UserDaoImpl() {
		super(User.class.getName());
	}

	@SuppressWarnings("unchecked")
	public List<User> getUsersByKeyword(String keyWord) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
        criteria.add(Restrictions.ilike("name", keyWord, MatchMode.ANYWHERE));
        criteria.add(Restrictions.eq("enable", true));
        return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
        criteria.add(Restrictions.eq("enable", true));
        return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("rawtypes")
	public User getByUsername(String username) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		criteria.add(Restrictions.eq("username", username));
		List result = getHibernateTemplate().findByCriteria(criteria);
		if(!result.isEmpty()){
			return (User) result.get(0);
		}
		
		return null;
	}

	public boolean existUser(String email) {
		DetachedCriteria criteria = DetachedCriteria.forEntityName(entityName);
		criteria.add(Restrictions.eq("email", email));
		return getHibernateTemplate().findByCriteria(criteria).size() > 0;
	}
}